package com.zlsy.thread.concurrentcontainer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author zhouliang
 * @date 2020/8/31 10:41
 * 演示CopyOnWriteArrayList可以在迭代的过程中修改数组的内容，但是ArrayList不行；
 * 进行对比操作；
 */
public class CopyOnWriteArrayListDemo {

    public static void main(String[] args) {
//        arrayListTest();
        copyOnWriteArrayListTest();
    }


    private static void arrayListTest() {
        ArrayList<String> list = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            list.add(i + "");
        }

        final Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println("list is " + list);
            final String next = iterator.next();
            System.err.println(next);
            //Exception in thread "main" java.util.ConcurrentModificationException
            if (next.equals("2")) {
                list.remove("3");
            }
            if (next.equals("4")) {
                list.add("0");
            }
        }
    }

    private static void copyOnWriteArrayListTest() {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

        for (int i = 1; i < 6; i++) {
            list.add(i + "");
        }


        final Iterator<String> iterator = list.iterator();
        //CopyOnWriteArrayList 你管你的修改，我管我的迭代；
        //互不干扰
        while (iterator.hasNext()) {
            /**
             * list is [1, 2, 3, 4, 5]
             * 1
             * list is [1, 2, 3, 4, 5]
             * 2
             * list is [1, 2, 3, 4]
             * 3
             * list is [1, 2, 3, 4, 3 no found]
             * 4
             * list is [1, 2, 3, 4, 3 no found]
             * 5
             */
            System.out.println("list is " + list);
            final String next = iterator.next();
            //list.remove("5") 还可以打印出5
            System.err.println(next);
            //Exception in thread "main" java.util.ConcurrentModificationException
            if (next.equals("2")) {
                list.remove("5");
            }
            if (next.equals("3")) {
                list.add("3 no found");
            }
        }
    }
}
